<template>
  <div class="edit-favorite">
    <div class="page-header">
      <el-button :icon="ArrowLeft" @click="$router.back()">返回</el-button>
      <h2>{{ isEditMode ? '编辑收藏' : '添加收藏' }}</h2>
    </div>

    <div v-if="loading" class="loading-state">
      <el-skeleton :rows="8" animated />
    </div>

    <el-form
      v-else
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="120px"
      class="favorite-form"
    >
      <el-form-item label="类型" prop="type" required>
        <el-radio-group v-model="form.type" @change="handleTypeChange">
          <el-radio-button label="text">文本/佳句</el-radio-button>
          <el-radio-button label="link">链接</el-radio-button>
          <el-radio-button label="image">图片</el-radio-button>
          <el-radio-button label="video">视频</el-radio-button>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="分类" prop="categoryId">
        <el-tree-select
            v-model="form.categoryId"
            :data="categories"
            placeholder="选择分类"
            clearable
            :render-after-expand="false"
            :default-expand-all="true"
            check-strictly="true"
            style="width: 100%"
            node-key="id"
            :props="{ label: 'name', children: 'children' }"
        />
      </el-form-item>

      <el-form-item label="标题" prop="title">
        <el-input
          v-model="form.title"
          placeholder="请输入标题"
          maxlength="200"
          show-word-limit/>
      </el-form-item>

      <!-- 文本类型的内容字段 -->
      <el-form-item v-if="form.type === 'text'" label="内容" prop="content">
        <el-input
          v-model="form.content"
          type="textarea"
          placeholder="请输入文本内容..."
          :rows="6"
          maxlength="2000"
          show-word-limit
        />
      </el-form-item>

      <!-- 链接、图片、视频类型的URL字段 -->
      <el-form-item 
        v-if="['link', 'image', 'video'].includes(form.type)" 
        :label="getUrlLabel(form.type)" 
        prop="url"
      >
        <el-input
          v-model="form.url"
          :placeholder="getUrlPlaceholder(form.type)"
          maxlength="1000"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="封面图片" prop="imageUrl">
        <el-input
          v-model="form.imageUrl"
          placeholder="请输入图片URL"
          maxlength="1000"
          show-word-limit
        />
        <div v-if="form.imageUrl" class="image-preview">
          <img :src="form.imageUrl" alt="预览" @error="handleImageError" />
        </div>
      </el-form-item>

      <el-form-item label="标签" prop="tags">
        <div class="tags-input">
          <el-tag
            v-for="tag in form.tags"
            :key="tag"
            closable
            @close="handleRemoveTag(tag)"
            class="tag-item"
          >
            {{ tag }}
          </el-tag>
          <el-input
            v-if="tagInputVisible"
            ref="tagInputRef"
            v-model="tagInputValue"
            class="tag-input"
            size="small"
            @keyup.enter="handleAddTag"
            @blur="handleAddTag"
            placeholder="输入标签按回车"
          />
          <el-button
            v-else
            class="button-new-tag"
            size="small"
            @click="showTagInput"
          >
            + 添加标签
          </el-button>
        </div>
      </el-form-item>

      <el-form-item label="出处" prop="source">
        <el-input
          v-model="form.source"
          placeholder="请输入出处"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="收藏状态">
        <el-switch
          v-model="form.isFavorite"
          active-text="已收藏"
          inactive-text="未收藏"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          保存修改
        </el-button>
        <el-button @click="handleReset">重置</el-button>
        <el-button @click="$router.back()">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElInput, type FormInstance, type FormRules } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'
import { categoryApi, favoriteItemApi } from '../api'
import type { CategoryListItem } from '../api'
import type { UpdateFavoriteItemRequest, FavoriteType, FavoriteItem } from '../types'

const router = useRouter()
const route = useRoute()
const formRef = ref<FormInstance>()
const loading = ref(true)
const submitting = ref(false)

// 标签输入相关
const tagInputVisible = ref(false)
const tagInputValue = ref('')
const tagInputRef = ref<InstanceType<typeof ElInput>>()

// 判断是编辑模式还是创建模式
const isEditMode = computed(() => !!route.params.id)

// 分类数据
const categories = ref<CategoryListItem[]>([])

// 表单数据
const form = reactive<UpdateFavoriteItemRequest & { type: FavoriteType }>({
  categoryId: '',
  title: '',
  content: '',
  url: '',
  imageUrl: '',
  tags: [],
  type: 'text' as FavoriteType,
  source: '',
  isFavorite: true
})

// 原始数据备份
let originalData: Partial<FavoriteItem> = {}

// 表单验证规则
const rules: FormRules = {
  categoryId: [
    { max: 200, message: '分类ID长度不能超过 200 个字符', trigger: 'blur' }
  ],
  title: [
    { max: 200, message: '标题长度不能超过 200 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择类型', trigger: 'change' }
  ],
  url: [
    {
      validator: (_rule, value, callback) => {
        if (['link', 'image', 'video'].includes(form.type) && !value) {
          callback(new Error('请输入URL'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 获取URL字段标签
const getUrlLabel = (type: string) => {
  switch (type) {
    case 'link':
      return '链接地址'
    case 'image':
      return '图片地址'
    case 'video':
      return '视频地址'
    default:
      return 'URL'
  }
}

// 获取URL字段占位符
const getUrlPlaceholder = (type: string) => {
  switch (type) {
    case 'link':
      return '请输入链接地址，如：https://www.example.com'
    case 'image':
      return '请输入图片地址'
    case 'video':
      return '请输入视频地址，如：B站、小红书等'
    default:
      return '请输入URL'
  }
}

// 处理类型变化
const handleTypeChange = (_type: FavoriteType) => {
  // 重新验证表单
  formRef.value?.clearValidate(['content', 'url'])
}

// 处理图片错误
const handleImageError = (event: Event) => {
  const img = event.target as HTMLImageElement
  img.style.display = 'none'
}

// 显示标签输入框
const showTagInput = () => {
  tagInputVisible.value = true
  nextTick(() => {
    tagInputRef.value?.focus()
  })
}

// 添加标签
const handleAddTag = () => {
  const value = tagInputValue.value.trim()
  if (value && !form.tags?.includes(value)) {
    if (!form.tags) {
      form.tags = []
    }
    form.tags.push(value)
  }
  tagInputVisible.value = false
  tagInputValue.value = ''
}

// 删除标签
const handleRemoveTag = (tag: string) => {
  const index = form.tags?.indexOf(tag)
  if (index !== undefined && index > -1) {
    form.tags?.splice(index, 1)
  }
}

// 加载分类
const loadCategories = async () => {
  try {
    categories.value = await categoryApi.list({ type: 'COLLECT' })
  } catch (error) {
    ElMessage.error('加载分类失败')
  }
}

// 加载收藏项数据
const loadFavoriteItem = async () => {
  const id = route.params.id as string

  // 如果是创建模式（没有ID），直接结束加载
  if (!id) {
    // 检查URL参数中是否有分类ID
    const categoryIdFromQuery = route.query.categoryId as string | undefined
    if (categoryIdFromQuery) {
      form.categoryId = categoryIdFromQuery
    }
    loading.value = false
    return
  }

  // 编辑模式：加载现有数据
  try {
    const item = await favoriteItemApi.getDetail(id)

    // 保存原始数据
    originalData = { ...item }

    // 填充表单
    Object.assign(form, {
      categoryId: item.categoryId,
      title: item.title,
      content: item.content || '',
      url: item.url || '',
      imageUrl: item.imageUrl || '',
      tags: item.tags || [],
      type: item.type,
      source: item.source || '',
      isFavorite: item.isFavorite
    })
  } catch (error) {
    ElMessage.error('加载收藏项失败')
    router.push('/collect')
  } finally {
    loading.value = false
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    submitting.value = true

    if (isEditMode.value) {
      // 编辑模式：更新现有收藏
      const id = route.params.id as string
      await favoriteItemApi.update(id, form)
      ElMessage.success('保存成功')
    } else {
      // 创建模式：新建收藏
      await favoriteItemApi.create(form)
      ElMessage.success('创建成功')
    }

    // 跳转回收藏列表，如果有分类ID则携带
    if (form.categoryId) {
      router.push({
        path: '/collect',
        query: { categoryId: form.categoryId }
      })
    } else {
      router.push('/collect')
    }
  } catch (error) {
    if (error !== false) { // 不是表单验证错误
      ElMessage.error(isEditMode.value ? '保存失败' : '创建失败')
    }
  } finally {
    submitting.value = false
  }
}

// 重置表单
const handleReset = () => {
  if (originalData) {
    Object.assign(form, {
      categoryId: originalData.categoryId,
      title: originalData.title,
      content: originalData.content || '',
      url: originalData.url || '',
      imageUrl: originalData.imageUrl || '',
      tags: originalData.tags || [],
      type: originalData.type,
      source: originalData.source || '',
      isFavorite: originalData.isFavorite
    })
  }
}

// 初始化
onMounted(async () => {
  await Promise.all([
    loadCategories(),
    loadFavoriteItem()
  ])
})
</script>

<style scoped>
.edit-favorite {
  padding: 24px;
  background: var(--el-bg-color-page);
  min-height: 100vh;
}

.page-header {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0;
  color: var(--el-text-color-primary);
}

.loading-state {
  max-width: 800px;
  background: var(--el-bg-color);
  padding: 24px;
  border-radius: 8px;
  border: 1px solid var(--el-border-color-light);
}

.favorite-form {
  max-width: 800px;
  background: var(--el-bg-color);
  padding: 24px;
  border-radius: 8px;
  border: 1px solid var(--el-border-color-light);
}

.image-preview {
  margin-top: 8px;
}

.image-preview img {
  max-width: 200px;
  max-height: 150px;
  object-fit: cover;
  border-radius: 4px;
  border: 1px solid var(--el-border-color-light);
}

.tags-input {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
}

.tag-item {
  margin: 0;
}

.tag-input {
  width: 120px;
}

.button-new-tag {
  height: 24px;
  line-height: 22px;
  padding: 0 8px;
}

:deep(.el-radio-button__inner) {
  border-radius: 4px !important;
}

:deep(.el-radio-button:first-child .el-radio-button__inner) {
  border-radius: 4px !important;
}

:deep(.el-radio-button:last-child .el-radio-button__inner) {
  border-radius: 4px !important;
}

/* 深色模式适配 */
.dark .edit-favorite {
  background: var(--el-bg-color-page);
}

.dark .loading-state,
.dark .favorite-form {
  background: var(--el-bg-color-overlay);
  border-color: var(--el-border-color);
}

.dark .page-header h2 {
  color: var(--el-text-color-primary);
}

.dark .image-preview img {
  border-color: var(--el-border-color);
}
</style>